/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bsk;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import komunikaty.*;
/**
 *
 * @author pd
 */

public class CardNS {

    //sprawdza karty
    public static boolean checkCards(Card[] cards, String pesel) {

        boolean ret = checkBlist(pesel);

        for (Card c : cards) {
            if (!checkCard(c)) {
                ret = false;
                break;
            }
        }
        
        if (!ret) addToBlackList(pesel);
        
        return ret;
    }
//ponizej sa privaty
    private static void addToBlackList(String pesel) {
        FileWriter blackList = null;
        try {
            blackList = new FileWriter(blackListName, true);
            PrintWriter out = new PrintWriter(blackList);
            out.println(pesel);
        } catch (IOException ex) {
            Logger.getLogger(CardNS.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                blackList.close();
            } catch (IOException ex) {
                Logger.getLogger(CardNS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private static boolean checkBlist(String pesel) {
        boolean ret = true;
        BufferedReader in = null;

        try {
            in = new BufferedReader(new FileReader(new File(blackListName)));
            //Scanner in = new Scanner(f);
            String mn;
            while ((mn = in.readLine()) != null) {
                if (pesel.equals(mn)) {
                    ret = false;
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(CardNS.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(CardNS.class.getName()).log(Level.SEVERE, null, ex);
            }
            return ret;
        }
    }

    private static boolean checkCard(Card c) {

        BigInteger serial = c.votes[0].serial;
        for (Card.Vote v : c.votes) {

            for (Card.Vote v2 : c.votes) {
                if (v != v2 && v.candidate.equals(v2.candidate)) {
                    return false;
                }
            }
            if (v.serial.compareTo(serial) != 0) {
                return false;
            }
        }

        return true;
    }
    private static String blackListName = "BlackList";
}